package com.honghu.villagepost.dao.manager;

import android.content.Context;

import com.homghu.villagepost.DaoMaster;
import com.homghu.villagepost.DaoSession;
import com.honghu.villagepost.dao.data.database.DatabaseOpenHelper;

import java.util.Locale;

/**
 * 作者: liyu on  2017/11/17 0017 12:56
 * 功能描述:数据库管理器
 * 备注:
 */
public class DbHelper {

    private static DbHelper mInstance;
    private Context mContext;
    private DaoSession mDaoSession;
    private String mUserId = "db";

    public static DbHelper getInstance() {
        synchronized (DbHelper.class) {
            if (mInstance == null) {
                mInstance = new DbHelper();
            }
        }
        return mInstance;
    }

    public DbHelper() {
    }

    public void init(Context context, String userId) {
        mContext = context;
        mUserId = userId;
    }

    public DaoSession getDaoSession() {
        if (mDaoSession == null) {
            DaoMaster.OpenHelper helper = new DatabaseOpenHelper(mContext, formatDatabaseName(mUserId),//每个用户会建一个数据库
                    null);
            DaoMaster mDaoMaster = new DaoMaster(helper.getWritableDatabase());
            mDaoSession = mDaoMaster.newSession();
        }
        return mDaoSession;
    }

    private String formatDatabaseName(String userId) {
        return String.format(Locale.getDefault(), "%s_%s", DbConstants.DB.NAME, userId);
    }

    public void clearDb() {
        mUserId = "";
        mDaoSession = null;
    }
}
